package com.autoagent.ai_live_master.scriptRecommendation.service.impl;

import com.autoagent.ai_live_master.common.utils.BeanConverter;
import com.autoagent.ai_live_master.scriptRecommendation.dto.LiveRoomDTO;
import com.autoagent.ai_live_master.scriptRecommendation.entity.LiveRoom;
import com.autoagent.ai_live_master.scriptRecommendation.mapper.LiveRoomMapper;
import com.autoagent.ai_live_master.scriptRecommendation.service.LiveRoomService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 直播间服务实现类
 */
@Slf4j
@Service
public class LiveRoomServiceImpl extends ServiceImpl<LiveRoomMapper,LiveRoom> implements LiveRoomService {

    @Override
    public List<LiveRoomDTO> getAllLiveRooms(Long userId) {
        log.info("开始获取用户 {} 的直播间列表", userId);
        try {
            LambdaQueryWrapper<LiveRoom> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LiveRoom::getUserId, userId);

            List<LiveRoom> liveRooms = this.list(queryWrapper);

            List<LiveRoomDTO> result = liveRooms.stream()
                    .map(liveRoom -> BeanConverter.convert(liveRoom, LiveRoomDTO.class))
                    .collect(Collectors.toList());

            log.info("获取直播间列表成功 - 数量: {}", result.size());
            return result;
        } catch (Exception e) {
            log.error("获取直播间列表失败 - 错误信息: {}", e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public Page<LiveRoomDTO> getPageByUserId(Long userId, Integer pageNum, Integer pageSize) {
        log.info("分页获取用户的直播间列表 - 用户ID: {}, 页码: {}, 每页大小: {}", userId, pageNum, pageSize);

        Page<LiveRoom> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<LiveRoom> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LiveRoom::getUserId, userId);

        // 按创建时间倒序排列
        wrapper.orderByDesc(LiveRoom::getCreatedAt);

        Page<LiveRoom> entityPage = this.page(page, wrapper);

        // 转换为DTO分页对象
        Page<LiveRoomDTO> dtoPage = new Page<>();
        dtoPage.setTotal(entityPage.getTotal());
        dtoPage.setCurrent(entityPage.getCurrent());
        dtoPage.setSize(entityPage.getSize());
        dtoPage.setRecords(entityPage.getRecords().stream()
                .map(entity -> BeanConverter.convert(entity, LiveRoomDTO.class))
                .collect(Collectors.toList()));

        return dtoPage;
    }

    @Override
    public void createLiveRoom(LiveRoom liveRoom) {
        log.info("开始创建直播间 - 直播间信息: {}", liveRoom);
        try {
            // 保存新直播间
            boolean success = this.save(liveRoom);
            if (success) {
                log.info("直播间创建成功 - id: {}", liveRoom.getId());
            } else {
                log.error("直播间创建失败");
                throw new RuntimeException("直播间创建失败");
            }
        } catch (Exception e) {
            log.error("创建直播间失败 - 错误信息: {}", e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public LiveRoomDTO updateLiveRoom(LiveRoom liveRoom) {
        log.info("开始更新直播间 - id: {}, 更新内容: {}", liveRoom.getId(), liveRoom);
        try {
            // 检查直播间是否存在
            LiveRoom existingLiveRoom = this.getById(liveRoom.getId());
            if (existingLiveRoom == null) {
                log.warn("更新直播间失败 - 直播间不存在, id: {}", liveRoom.getId());
                return null;
            }
            // 直播间存在，执行更新
            boolean success = this.updateById(liveRoom);
            if (!success) {
                log.error("更新直播间失败 - id: {}", liveRoom.getId());
                throw new RuntimeException("更新直播间失败");
            }
            // 重新获取更新后的直播间信息
            LiveRoom updatedLiveRoom = this.getById(liveRoom.getId());
            LiveRoomDTO result = BeanConverter.convert(updatedLiveRoom, LiveRoomDTO.class);
            log.info("更新直播间成功 - id: {}", liveRoom.getId());
            return result;
        } catch (Exception e) {
            log.error("更新直播间失败 - id: {}, 错误信息: {}", liveRoom.getId(), e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public boolean deleteLiveRoom(Integer id) {
        log.info("开始删除直播间 - id: {}", id);
        try {
            // 检查直播间是否存在
            LiveRoom existingLiveRoom = this.getById(id);
            if (existingLiveRoom == null) {
                log.warn("删除直播间失败 - 直播间不存在, id: {}", id);
                return false;
            }
            // 直播间存在，执行删除
            boolean success = this.removeById(id);
            if (success) {
                log.info("删除直播间成功 - id: {}", id);
            } else {
                log.error("删除直播间失败 - id: {}", id);
                throw new RuntimeException("删除直播间失败");
            }
            return true;
        } catch (Exception e) {
            log.error("删除直播间失败 - id: {}, 错误信息: {}", id, e.getMessage(), e);
            throw e;
        }
    }
}